#!/usr/bin/env python
# encoding: utf-8

"""
LGNotifier.py

Copyright (c) 2007, Adrian Petrescu

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * The names of its contributors may not be used to endorse or promote
      products derived from this software without specific prior written
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

import sys
import os
from urllib import urlencode
from Notifier import Notifier
from Notifier import LoginException
from Notifier import CookieNotSetException
from Notifier import ServerNotReachableException
from Game import GoGame, ChessGame

class LGNotifier(Notifier):
   
   COOKIEFILE = "lg_cookie.lwp"
   LG_LOGIN_URL = "http://www.littlegolem.net/jsp/login/index.jsp"
   LG_STATUS_URL = "http://www.littlegolem.net/jsp/game/index.jsp"
   cj = None
   Request = None
   urlopen = None
   cookielib = None
   username = "AdrianP"
   
   def checkLoginStatus(self):
      data = None
      headers = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
      try:
         req = self.Request(self.LG_STATUS_URL, data, headers)
         handle = self.urlopen(req)
         if "Input Your Login Name and Password." in handle.read():
            return False
         else:
            print handle.read()
            return True
      except IOError:
         raise ServerNotReachableException()

   def login(self):
      if self.checkLoginStatus():
         return True
      data = urlencode({'login' : self.username , 'password' : self.password})
      headers = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
      req = self.Request(self.LG_LOGIN_URL, data, headers)
      handle = self.urlopen(req)
      if "You have successfully logged in" in handle.read():
         self.cj.save(self.COOKIEFILE)
         return True
      else:
         return False
   
   def __init__(self):
      try:
         import cookielib
      except ImportError:
         pass
      else:
         import urllib2
         self.urlopen = urllib2.urlopen
         self.cj = cookielib.LWPCookieJar()
         self.Request = urllib2.Request
      
      if not self.cookielib:
         try:
            import ClientCookie
         except ImportError:
            import urllib2
            self.urlopen = urllib2.urlopen
            self.Request = urllib2.Request
         else:
            self.urlopen = ClientCookie.urlopen
            self.cj = ClientCookie.LWPCookieJar()
            self.Request = ClientCookie.Request
            
      if self.cj != None:
         if os.path.isfile(self.COOKIEFILE):
            self.cj.load(self.COOKIEFILE)
         if self.cookielib:
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
            urllib2.install_opener(opener)
         else:
            opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(self.cj))
            ClientCookie.install_opener(opener)

if __name__ == '__main__':
   t = LGNotifier()
   print t.login()
   print t.checkLoginStatus()
